package com.ziru.ziru.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ziru.ziru.dao.TenantDao;
import com.ziru.ziru.pojo.Tenant;
import com.ziru.ziru.service.TenantService;
import com.ziru.ziru.utils.RandomName;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Service
public class TenantServiceImpl extends ServiceImpl<TenantDao, Tenant> implements TenantService {
    @Resource
    private TenantDao tenantDao;

    @Override
    public Tenant login(Tenant tenant, HttpSession session) {
        String tEmail = tenant.getEmail();
        String tPhone = tenant.getPhone();
        String tNickname = tenant.getNickname();
        Tenant user = this.getOne(new LambdaQueryWrapper<Tenant>().eq(StringUtils.isNotBlank(tPhone),
                        Tenant::getPhone, tPhone).or()
                .eq(StringUtils.isNotBlank(tEmail), Tenant::getEmail, tEmail).or()
                .eq(StringUtils.isNotBlank(tNickname), Tenant::getEmail, tEmail));
        if (user == null){
            return null;
        }
        return user;
    }


    @Override
    public int Register(@RequestBody Tenant tenant) {
        String phone = tenant.getPhone();
        // 判断手机号是否重复
        Tenant res = this.getOne(new LambdaQueryWrapper<Tenant>()
                .eq(StringUtils.isNotBlank(phone),
                Tenant::getPhone, phone));
        if (res == null){
            // 随机生成名字   格式   自如客+5个随机生成英文字母或者数字
            RandomName randomName = new RandomName();
            String name = randomName.getRandomName();
            tenant.setNickname("自如客"+name);
            // 添加数据
            int i = tenantDao.insert(tenant);
            return i;
        }

        return 0;
    }

}
